'use strict';

const AWS = require('aws-sdk')
const config = require('../config')
const bluebird = require('bluebird')
const Consumer = require('sqs-consumer')


const {
    accessKeyId,
    secretAccessKey
} = config.aws.s3

AWS.config.setPromisesDependency(bluebird)
AWS.config.update({ accessKeyId, secretAccessKey })

const sqs = new AWS.SQS({
    region: 'cn-north-1',
    accessKeyId,
    secretAccessKey
})


exports.createQueue = function(queue) {
    return sqs.createQueue({
        QueueName: `sophic-${config.aws.env}-${queue}`
    }).promise()
}

exports.deleteQueue = function(QueueUrl) {
    return sqs.deleteQueue({
        QueueUrl
    }).promise()
}

exports.getQueueUrl = function(QueueName) {
    return sqs.getQueueUrl({
        QueueName
    }).promise()
}

exports.listQueues = function() {
    return sqs.listQueues().promise()
}

exports.sendMessage = function(queue, message) {
    return sqs.sendMessage({
        QueueUrl: `${config.aws.sqs}/sophic-${config.aws.env}-${queue}`,
        MessageBody: JSON.stringify(message)
    }).promise()
}

exports.sendMessageBatch = function(queue, Entries) {
    return sqs.sendMessageBatch({
        QueueUrl: `${config.aws.sqs}/sophic-${config.aws.env}-${queue}`,
        Entries
    }).promise()
}

exports.consumer = function(queue, handleMessage) {
    return Consumer.create({
        queueUrl: `${config.aws.sqs}/sophic-${config.aws.env}-${queue}`,
        handleMessage,
        sqs
    })
}